package com.qys.livesMall.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.common.utils.DateUtils;
import com.qys.livesMall.system.mapper.H2SysConfigMapper;
import com.qys.livesMall.system.model.dto.app.SysConfigSaveReq;
import com.qys.livesMall.system.model.dto.sys.SysConfigQuery;
import com.qys.livesMall.system.model.entity.H2SysConfig;
import com.qys.livesMall.system.model.vo.app.SysConfigGroupVO;
import com.qys.livesMall.system.model.vo.sys.H2SysConfigVO;
import com.qys.livesMall.system.service.IH2SysConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author caoz
 * @since 2023-04-20
 */
@Service
public class H2SysConfigServiceImpl extends ServiceImpl<H2SysConfigMapper, H2SysConfig> implements IH2SysConfigService {

    private static final String SYS_CONFIG_REDIS_KEY = "sys:config:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public int add(H2SysConfigVO params) {
//        Assert.notEmpty(params.getTitle(), "字段名称不能为空！");
//        Assert.notNull(params.getType(), "字段类型不能为空！");
        H2SysConfig h2SysConfig=new H2SysConfig();
        BeanUtil.copyProperties(params,h2SysConfig);
        h2SysConfig.setCreateTime(LocalDateTime.now());
        h2SysConfig.setUpdateTime(LocalDateTime.now());
        //生成key
        h2SysConfig.setKey(UUID.randomUUID().toString().replace("-", ""));
        save(h2SysConfig);
        delRedisCache(h2SysConfig);
        return 1;
    }

    @Override
    public int put(H2SysConfigVO params) {
//        Assert.notNull(params.getId(), "id不能为空！");
//        Assert.notEmpty(params.getTitle(), "字段名称不能为空！");
        Assert.notNull(params.getType(), "字段类型不能为空！");
        H2SysConfig h2SysConfig=new H2SysConfig();
        BeanUtil.copyProperties(params,h2SysConfig);
        h2SysConfig.setUpdateTime(LocalDateTime.now());
        updateById(h2SysConfig);
        delRedisCache(h2SysConfig);
        return 1;
    }

    @Override
    public Page<?> pageList(SysConfigQuery query) {
        return baseMapper.pageList(new Page<>(query.getPageNum(), query.getPageSize()), query);
    }

    @Override
    public List<H2SysConfig> listConfigByGroup(int groupId) {
        //先去redis查询
        String key = SYS_CONFIG_REDIS_KEY + groupId;
        String configJson = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(configJson)) {
            return JSONUtil.toList(configJson, H2SysConfig.class);
        }
        LambdaQueryWrapper<H2SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(H2SysConfig::getGroupId, groupId);
        List<H2SysConfig> list = baseMapper.selectList(wrapper);
        //放入redis缓存
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(list));
        return list;
    }

    @Override
    public List<SysConfigGroupVO> listGroup() {
        LambdaQueryWrapper<H2SysConfig> wrapper = new LambdaQueryWrapper<>();
        String key = SYS_CONFIG_REDIS_KEY + "group";
        String configJson = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(configJson)) {
            return JSONUtil.toList(configJson, SysConfigGroupVO.class);
        }
        //查询全部的平台分组配置
        List<H2SysConfig> list = baseMapper.selectList(wrapper);
        //子节点分组
        Map<String, List<SysConfigGroupVO>> childMap = list.stream().filter(item -> Objects.nonNull(item.getGroupId())).map(item -> {
            SysConfigGroupVO sysConfigGroupVO = new SysConfigGroupVO();
            BeanUtils.copyProperties(item, sysConfigGroupVO);
            return sysConfigGroupVO;
        }).collect(Collectors.groupingBy(SysConfigGroupVO::getGroupId));
        //组装分组下的节点以及起子节点
        List<SysConfigGroupVO> groupList = list.stream().filter(item -> Objects.isNull(item.getGroupId())).map(item -> {
            SysConfigGroupVO sysConfigGroupVO = new SysConfigGroupVO();
            BeanUtils.copyProperties(item, sysConfigGroupVO);
            sysConfigGroupVO.setChildList(childMap.get(item.getId()));
            return sysConfigGroupVO;
        }).collect(Collectors.toList());

        if (!groupList.isEmpty()) {
            //分组信息放到redis
            redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(groupList));
        }
        return groupList;
    }

    @Override
    public int formSave(SysConfigSaveReq data) {
        //批量保存表单接口
        Assert.isTrue(null != data && !CollectionUtils.isEmpty(data.getData()), "表单数据不能为空！");
        List<H2SysConfig> list = data.getData().stream().filter(item -> item.getValue() != null).map(item -> {
            H2SysConfig config = new H2SysConfig();
            config.setId(item.getId());
            config.setKey(item.getKey());
            //type 4 为富文本类型 字典项
            if ("4".equals(item.getType())) {
                config.setRichText(item.getRichText());
            } else {
                config.setValue(item.getValue());
            }
            return config;
        }).toList();

        //批量更新
        for (H2SysConfig h2SysConfig : list) {
            baseMapper.updateByKey(h2SysConfig);
        }
        delRedisCache(data.getData().get(0));
        return 1;
    }

    @Override
    public H2SysConfig getConfigByKey(String key) {
        return getOne(Wrappers.<H2SysConfig>lambdaQuery().eq(H2SysConfig::getKey, key));
    }

    @Override
    public String getConfigKey(String key) {
        H2SysConfig h2SysConfig=getConfigByKey(key);
        if (null == h2SysConfig){
            return null;
        }
        return h2SysConfig.getValue();
    }

    @Override
    public Map getConfigKeys(List<String> keys) {
       List<H2SysConfig> list= list(Wrappers.<H2SysConfig>lambdaQuery().in(H2SysConfig::getKey, keys));
       if (list==null){
           return new HashMap();
       }
       Map map=new HashMap();
       for(H2SysConfig config:list){
           map.put(config.getKey(),config.getValue());
       }
        return map;
    }

    @Override
    public List<String> getConfigServiceAddress() {
        LambdaQueryWrapper<H2SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(H2SysConfig::getTitle, "客服地址");
        wrapper.orderByAsc(H2SysConfig::getTitle);
        List<H2SysConfig> list = baseMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(list)){
            List<String> arr=list.stream().map(H2SysConfig::getValue).collect(Collectors.toList());
            return arr;
        }
        return null;
    }

    @Override
    public List<H2SysConfig> getConfigByKeys(List<String> keys) {
        return list(Wrappers.<H2SysConfig>lambdaQuery().in(H2SysConfig::getKey, keys));
    }

    private void delRedisCache(H2SysConfig params) {
        if (null != params.getGroupId()) {
            //删除redis缓存
            redisTemplate.delete(SYS_CONFIG_REDIS_KEY + params.getGroupId());
        }
        redisTemplate.delete(SYS_CONFIG_REDIS_KEY + "group");
    }
}
